/*
 *    Copyright 2009-2022 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.reflection;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.reflection.wrapper.BeanWrapper;
import org.apache.ibatis.reflection.wrapper.CollectionWrapper;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;

/**
 * 元对象,mybatis相对底层的工具类
 * 会对对象进行一系列的包装,包装后,反射时能直接操作对象属性
 * <p>
 * 可以直接操作属性
 * 操作子属性
 * 自动创建属性对象
 * 自动查找属性名  支持下划线驼峰
 * 支持数组访问(基于索引) list[0].author.name 数组必须手动创建
 * 支持Map访问 map[key]
 * 支持访问对象 map[key].name
 * <p>
 * <p>
 * Mybatis映射体系
 * {@linkplain MetaObject 元对象} 的 ObjectWrapper 属性   操作属性
 * {@linkplain BeanWrapper bean的包装对象} 的 MetaClass 属性  操作属性的属性
 * {@linkplain MetaClass 元类} 的  Reflector 属性  获取class对象
 * {@linkplain Reflector 反射器}  获取当前class的值
 *
 * @author Clinton Begin
 */
public class MetaObject {

  /**
   * 原始对象 自己的对象
   */
  private final Object originalObject;
  /**
   * 对象包装器  具体实现为 {@linkplain BeanWrapper}
   */
  private final ObjectWrapper objectWrapper;
  /**
   * 对象工厂
   */
  private final ObjectFactory objectFactory;
  /**
   * 对象包装器工厂
   */
  private final ObjectWrapperFactory objectWrapperFactory;
  /**
   * 反射工厂
   */
  private final ReflectorFactory reflectorFactory;

  private MetaObject(Object object, ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory, ReflectorFactory reflectorFactory) {
    this.originalObject = object;
    this.objectFactory = objectFactory;
    this.objectWrapperFactory = objectWrapperFactory;
    this.reflectorFactory = reflectorFactory;

    if (object instanceof ObjectWrapper) {
      this.objectWrapper = (ObjectWrapper) object;
    } else if (objectWrapperFactory.hasWrapperFor(object)) {
      this.objectWrapper = objectWrapperFactory.getWrapperFor(this, object);
    } else if (object instanceof Map) {
      this.objectWrapper = new MapWrapper(this, (Map) object);
    } else if (object instanceof Collection) {
      this.objectWrapper = new CollectionWrapper(this, (Collection) object);
    } else {
      this.objectWrapper = new BeanWrapper(this, object);
    }
  }

  public static MetaObject forObject(Object object, ObjectFactory objectFactory, ObjectWrapperFactory objectWrapperFactory, ReflectorFactory reflectorFactory) {
    if (object == null) {
      return SystemMetaObject.NULL_META_OBJECT;
    } else {
      return new MetaObject(object, objectFactory, objectWrapperFactory, reflectorFactory);
    }
  }

  public ObjectFactory getObjectFactory() {
    return objectFactory;
  }

  public ObjectWrapperFactory getObjectWrapperFactory() {
    return objectWrapperFactory;
  }

  public ReflectorFactory getReflectorFactory() {
    return reflectorFactory;
  }

  public Object getOriginalObject() {
    return originalObject;
  }

  /**
   * 查找属性
   *
   * @param propName            属性名
   * @param useCamelCaseMapping 是否进行驼峰命名
   * @return
   */
  public String findProperty(String propName, boolean useCamelCaseMapping) {
    return objectWrapper.findProperty(propName, useCamelCaseMapping);
  }

  public String[] getGetterNames() {
    return objectWrapper.getGetterNames();
  }

  public String[] getSetterNames() {
    return objectWrapper.getSetterNames();
  }

  public Class<?> getSetterType(String name) {
    return objectWrapper.getSetterType(name);
  }

  public Class<?> getGetterType(String name) {
    return objectWrapper.getGetterType(name);
  }

  public boolean hasSetter(String name) {
    return objectWrapper.hasSetter(name);
  }

  public boolean hasGetter(String name) {
    return objectWrapper.hasGetter(name);
  }

  /**
   * 通过属性名获取值  可以通过多层获取
   * <p>
   * 以   comments[0].user.name  举例
   *
   * @param name
   * @return
   */
  public Object getValue(String name) {
    // 创建属性分词器,对属性进行分词
    PropertyTokenizer prop = new PropertyTokenizer(name);
    // 是否存在子属性
    if (prop.hasNext()) {
      // 存在子属性,获取子属性,会递归调用此方法
      MetaObject metaValue = metaObjectForProperty(prop.getIndexedName());
      // 判断对象是不是空  如果不是空表示还有子属性
      if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
        return null;
      } else {
        // 还存在子属性,递归获取
        return metaValue.getValue(prop.getChildren());
      }
    } else {
      /**
       * 不存在子属性,直接获取值
       * {@linkplain BeanWrapper#get(org.apache.ibatis.reflection.property.PropertyTokenizer)}
       */
      return objectWrapper.get(prop);
    }
  }

  /**
   * 设置属性值
   *
   * @param name  属性名
   * @param value 属性值
   */
  public void setValue(String name, Object value) {

    PropertyTokenizer prop = new PropertyTokenizer(name);

    if (prop.hasNext()) {

      MetaObject metaValue = metaObjectForProperty(prop.getIndexedName());

      if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
        if (value == null) {
          // don't instantiate child path if value is null
          return;
        } else {

          metaValue = objectWrapper.instantiatePropertyValue(name, prop, objectFactory);
        }
      }

      metaValue.setValue(prop.getChildren(), value);
    } else {
      /**
       * 设置bean属性
       * {@linkplain BeanWrapper#set(org.apache.ibatis.reflection.property.PropertyTokenizer, java.lang.Object)}
       */
      objectWrapper.set(prop, value);
    }
  }

  /**
   * 获取属性值
   *
   * @param name
   * @return
   */
  public MetaObject metaObjectForProperty(String name) {
    // 递归获取
    Object value = getValue(name);
    // 获取到对象,将对象包装成  MetaObject , 底层值接new出来的,并给 MetaObject 赋值
    return MetaObject.forObject(value, objectFactory, objectWrapperFactory, reflectorFactory);
  }

  public ObjectWrapper getObjectWrapper() {
    return objectWrapper;
  }

  public boolean isCollection() {
    return objectWrapper.isCollection();
  }

  public void add(Object element) {
    objectWrapper.add(element);
  }

  public <E> void addAll(List<E> list) {
    objectWrapper.addAll(list);
  }

}
